﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Mvc;

namespace MKAdmin.Injection
{
    public static class IOCFactory
    {
        /// <summary>
        /// 注入接口组件 
        /// </summary>
        private static readonly Ninject.IKernel _kernel = new Ninject.StandardKernel();

        /// <summary>
        /// 加载类型
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="nameSpace"></param>
        private static void LoaderType()
        {
            Assembly asm = Assembly.Load("MKAdmin.ServiceImpl");
            Type[] types = asm.GetTypes().Where(
                x => x.IsPublic && x.IsClass).ToArray();

            BindingType bt = new BindingType();
            Type typeBind = typeof(BindingType);
            MethodInfo method = null;

            foreach (Type type in types)
            {
                var baseInterface = type.GetInterfaces();
                if (!baseInterface.Any()) continue;
                foreach (var baseInfo in baseInterface)
                {
                    method = typeBind.GetMethod("Bind");
                    method = method.MakeGenericMethod(baseInfo, type);
                    method.Invoke(bt, new object[] { _kernel });
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void Register()
        {
            LoaderType();
            GlobalConfiguration.Configuration.DependencyResolver = new ApiDependencyResolver(_kernel);
            //NinjectDependencyResolver resolver = new NinjectDependencyResolver(_kernel);
            DependencyResolver.SetResolver(new NinjectDependencyResolver(_kernel));
        }

        /// <summary>
        /// 获取 实例对象　
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return DependencyResolver.Current.GetService<T>();
        }


    }
}
